package org.jeecg.modules.car.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.ForeignResult;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.RedisKeyConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ComUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.config.Sm4Util;
import org.jeecg.entity.car.CarDerateDetails;
import org.jeecg.entity.car.CarInfo;
import org.jeecg.entity.car.CarOrder;
import org.jeecg.entity.car.CarPort;
import org.jeecg.entity.charge.ChargeInvoiceRequest;
import org.jeecg.enums.InvoiceTypeEnum;
import org.jeecg.enums.PayModeEnum;
import org.jeecg.enums.PayStatusEnum;
import org.jeecg.enums.car.*;
import org.jeecg.enums.common.PayTypeEnum;
import org.jeecg.enums.meter.RefundStatusEnum;
import org.jeecg.lock.client.RedissonLockClient;
import org.jeecg.model.car.reqvo.CarDayReportReqVo;
import org.jeecg.model.car.respvo.CarDayReportRespVo;
import org.jeecg.model.charge.reqvo.DayReportReqVo;
import org.jeecg.model.charge.resvo.DayReportRespVo;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.entity.CarPayConfig;
import org.jeecg.modules.car.entity.CarPayNotify;
import org.jeecg.modules.car.mapper.CarOrderMapper;
import org.jeecg.modules.car.service.*;
import org.jeecg.modules.system.entity.FFTCreateOrder;
import org.jeecg.modules.system.entity.FFTFeeItem;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.car.ForeignCarIotPayTempReq;
import org.jeecg.vo.car.ForeignCarMonthlyRentReq;
import org.jeecg.vo.car.ForeignCarShPayCallBackReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 车禁订单
 * @Author: jeecg-boot
 * @Date:   2020-09-16
 * @Version: V1.0
 */
@Slf4j
@Service
public class CarOrderServiceImpl extends ServiceImpl<CarOrderMapper, CarOrder> implements ICarOrderService {
//    private final Queue<String> payQueue = new ConcurrentLinkedQueue<String>();
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private CarOrderMapper carOrderMapper;
    @Autowired
    private ForeignCarJGSService foreignCarJGSService;
    @Autowired
    private ICarDerateDetailsService derateDetailsService;
    @Autowired
    private ICarParkInfoService carParkInfoService;
    @Autowired
    private RedissonLockClient lockClient;
    @Autowired
    private ICarPortService carPortService;
    @Autowired
    private IFeignChargeService feignChargeService;


    @Value("${pay.fftEncryptKey}")
    private String fftEncryptKey; //付费通加密key

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Result<CarOrder> unLineCharge(CarOrder carOrder) throws ParseException {
        LoginUser user = SsoUtil.getLoginUser();
        Date now = new Date();
//        try {
            if (carOrder.getMonths() == null || carOrder.getMonths() <= 0 ) return Result.error("充值月数非法！");
            CarInfo carInfo =  carInfoService.getByCarId(carOrder.getCarId());
            if (carInfo == null) return Result.error("车辆未查到");
            if(carInfo.getStatus().equals(CarStatusEnum.SYNC_STATUS_STOP.getCode())){
                return Result.error("已经停用车辆无法缴费");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //当天日期
            Date date = sdf.parse(DateUtils.date2Str(new Date(),DateUtils.date_sdf));
            if (!carInfo.getCheckStatus().equals(CheckStatusEnum.CHECK_STATUS_YES.getCode())){
                return Result.error("车辆还未审核通过,无法充值！");
            }
//            if (carOrder.getCoverStartTime().compareTo(date) < 0){
//                return Result.error("计费开始日期不能小于当前日期");
//            }
            if (CarChargeTypeEnum.CHARGE_TYPE_NORMAL.getCode().equals(carOrder.getChargeType()+"") && carInfo.getLocalEndTime() != null){
                //当前车辆到期日后一天
                Date dt =  DateUtils.addDate(carInfo.getLocalEndTime(),1);
                String str = DateUtils.date2Str(dt,DateUtils.date_sdf);
                if (!DateUtils.date2Str(carOrder.getCoverStartTime(),DateUtils.date_sdf).equals(str)){
                    return Result.error("正常缴费车辆开始时间需为到期日后一天");
                }
            }
            if (carInfo.getLocalEndTime() != null && carOrder.getCoverStartTime().compareTo(carInfo.getLocalEndTime()) < 0){
                return Result.error("开始计费日期不能小于当前车辆的月卡到期日！");
            }
            //未到期
            /*if (carInfo.getLocalEndTime() != null && carInfo.getLocalEndTime().compareTo(date) > 0){
                //只能充值到期日后一天
                if (carOrder.getCoverStartTime().compareTo(carInfo.getLocalEndTime()) < 0){
                    return  Result.error("当前车辆月卡未到期，开始计费日期只能为["+ DateUtils.date2Str(date,DateUtils.date_sdf) +"]");
                }
            }*/
            /*else {
                //已到期
                carInfo.setLocalStartTime(carOrder.getCoverStartTime());
            }*/
            String sn = StringUtils.createSn(carInfo.getProjectCode(), 3);
            //上一次的缴费截止日期
            carOrder.setPrevEndTime(carInfo.getLocalEndTime());
            //上一次缴费开始日期
            carOrder.setPrevStartTime(carInfo.getLocalStartTime());
            carOrder.setCarNo(carInfo.getCarNo());
            carOrder.setParkId(carInfo.getParkId());
            carOrder.setSn(sn);
            carOrder.setCarTypeName(carInfo.getCarTypeName());
            carOrder.setOrderType(CarOrderTypeEnum.ORDER_TYPE_MONTHS.getCode()); //月卡
            carOrder.setCheckStatus(CheckStatusEnum.CHECK_STATUS_YES.getCode());
            carOrder.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode()); //默认未同步
            carOrder.setPayStatus(PayStatusEnum.PAY_STATUS_YES.getCode());
            carOrder.setPayMode(PayModeEnum.PAY_MODE_OFFLINE.getCode());
            carOrder.setUserId(carInfo.getOwnerId()); //业主id
            carOrder.setUserMobile(carInfo.getMobile()); //车主号码
            if (carOrder.getPayTime() == null){
                carOrder.setPayTime(new Date());
            }
            carOrder.setTenantId(user.getTenantId());

            //正常缴费 && 不是首次缴费只更新结束时间
            if((carOrder.getChargeType() == null || CarChargeTypeEnum.CHARGE_TYPE_NORMAL.getCode().equals(carOrder.getChargeType()+"")) && carOrder.getPrevEndTime() != null ){
                carInfo.setLocalEndTime(carOrder.getCoverEndTime());
            }else {
                carInfo.setLocalStartTime(carOrder.getCoverStartTime());
                carInfo.setLocalEndTime(carOrder.getCoverEndTime());
            }
            //更新车辆表
            carInfoService.updateFeeDate(carInfo);
            //更新车位信息
            if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                if (carPort == null){
                    return Result.error("未查询到当前车辆车位信息");
                }
                carOrder.setCarPortId(carPort.getId());
                carOrder.setCarPortNum(carPort.getCarportNum());
                //车位第一次续费需要更新开始时间
                if (carPort.getLocalStartTime() == null){
                    carPort.setLocalStartTime(carInfo.getLocalStartTime());
                }
                carPort.setLocalEndTime(carInfo.getLocalEndTime());
                carPortService.updateById(carPort);
                List<CarInfo> infoList =  carInfoService.getByCarPortId(carInfo.getCarPortId());
                for (CarInfo info : infoList){
                    //更新车位其他车辆信息（剔除上面已经更新的车辆 && 月卡开始结束时间相同车辆（ab临停））
                    if (!info.getCarNo().equals(carInfo.getCarNo()) && !info.getLocalStartTime().equals(info.getLocalEndTime())){
                        info.setLocalEndTime(carInfo.getLocalEndTime());//车位不能断缴只用修改结束时间
                        carInfoService.updateFeeDate(info);
                    }
                }
            }
            carOrderMapper.insert(carOrder);
            // 发票
            carOrder.setFeeItemId(carInfo.getFeeitemId());
            this.carBlueInvoice(carOrder);

            //插入账单表
            /*List<ChargeBills> billsList = new ArrayList<ChargeBills>();
            String year = DateUtils.formatDate(carOrder.getCoverStartTime(), "yyyy");
            String menth = DateUtils.formatDate(carOrder.getCoverStartTime(), "MM");
            for(int i=0;i < carOrder.getMonths();i++){
                ChargeBills bills = new ChargeBills();
                bills.setId(UUID.randomUUID().toString().replace("-", ""));
                bills.setCarDjid(carOrder.getCarId());
                bills.setCarCwid(carOrder.getCarCwid());
                bills.setZjCny(year +"-"+ (Integer.parseInt(menth)+i));
                billsList.add(bills);
            }*/
//            //纸制发票与收据
//            if(carOrder != null && carOrder.getInvoiceStatus().equals("2")){
//                String invoiceId = chargeInvoiceService.getIdByInoivce(carOrder.getInvoiceHm(), carOrder.getInvoiceDm());
//                if(null != invoiceId){
//                    ChargeInvoice invoice = new ChargeInvoice();
//                    invoice.setId(invoiceId);
//                    invoice.setUpdateBy(user.getId());
//                    invoice.setUpdateDate(new Date());
//                    invoice.setCwId(carOrder.getCarCwid());
//                    invoice.setDjId(carOrder.getCarId());
//                    invoice.setMakeInvoiceDate(carOrder.getPayTime());
//                    invoice.setZjSkrq(carOrder.getPayTime());
//                    invoice.setMoney(carOrder.getPayAmount().doubleValue());
//                    invoice.setPayMethod(Integer.valueOf(carOrder.getPayType()));
//                    invoice.setInvoiceMan(user.getUsername());
//                    invoice.setPayee(user.getUsername());
//                    invoice.setAddress(carOrder.getCarNo());
//                    invoice.setRemarks(carOrder.getPayMemo());
//                    chargeInvoiceService.updateInvoices(invoice);
//                    //票据详情
//                    List<ChargeInvoiceInfo> infolist =new ArrayList<ChargeInvoiceInfo>();
//                    ChargeInvoiceInfo info = new ChargeInvoiceInfo();
//                    Double sum = (carOrder.getPayDue().doubleValue()/carOrder.getMonths());
//                    String dates = DateUtils.date2Str(carOrder.getCoverStartTime(),new SimpleDateFormat("yyyy-MM")) + "～"+ DateUtils.date2Str(carOrder.getCoverEndTime(),new SimpleDateFormat("yyyy-MM"));
//                    info.setInvoiceDm(carOrder.getInvoiceDm());
//                    info.setInvoiceHm(carOrder.getInvoiceHm());
//                    info.setInvoiceId(invoiceId);
//                    info.setCreateBy(user.getId());
//                    info.setUpdateBy(user.getId());
//                    info.setUpdateDate(now);
//                    info.setCreateDate(now);
//                    info.setInvoiceObject("停车费");
//                    info.setNum(carOrder.getMonths());
//                    info.setUnit("月");
//                    info.setUnitPrice(sum);
//                    info.setMoney(carOrder.getPayAmount().doubleValue());
//                    info.setAbstractInfo(dates);
//                    infolist.add(info);
//                    chargeInvoiceService.insertInfos(infolist);
//                }
//             }
            return Result.ok(carOrder);
//        }catch (Exception e){
//            log.error("月卡车下线续费异常:{}",e);
//            throw e;
//        }
    }

    @Override
    public Result unLineQRCodeCharge(CarOrder carOrder) throws ParseException{
        LoginUser user = SsoUtil.getLoginUser();
        Date now = new Date();
        if (carOrder.getMonths() == null || carOrder.getMonths() <= 0 ) return Result.error("充值月数非法！");
        CarInfo carInfo =  carInfoService.getByCarId(carOrder.getCarId());
        if (carInfo == null) return Result.error("车辆未查到");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //当天日期
        Date date = sdf.parse(DateUtils.date2Str(new Date(),DateUtils.date_sdf));
        if (!carInfo.getCheckStatus().equals(CheckStatusEnum.CHECK_STATUS_YES.getCode())){
            return Result.error("车辆还未审核通过,无法充值！");
        }
        if (StringUtils.isNotBlank(carInfo.getCarPortId())){
            CarPort carPort = carPortService.getById(carInfo.getCarPortId());
            if (carPort == null){
                return Result.error("未查询到当前车辆绑定的车位信息");
            }
            carOrder.setCarPortId(carPort.getId());
            carOrder.setCarPortNum(carPort.getCarportNum());
        }
        if (carInfo.getLocalEndTime() != null && carOrder.getCoverStartTime().compareTo(carInfo.getLocalEndTime()) < 0){
            return Result.error("开始计费日期不能小于当前车辆的月卡到期日！");
        }
        //未到期
        if (carInfo.getLocalEndTime() != null && carInfo.getLocalEndTime().compareTo(date) > 0){
            //只能充值到期日后一天
            if (carOrder.getCoverStartTime().compareTo(carInfo.getLocalEndTime()) < 0){
                return  Result.error("当前车辆月卡未到期，开始计费日期只能为["+ DateUtils.date2Str(date,DateUtils.date_sdf) +"]");
            }
        }
        CarPayConfig payConfig = carOrderMapper.getCarPayConfig(carOrder.getParkId(), "scanner");
        if (payConfig == null){
            return Result.error("车场未配置支付参数");
        }
        String sn = StringUtils.createSn(carInfo.getProjectCode(), 3);
        //上一次的缴费截止日期
        carOrder.setPrevEndTime(carInfo.getLocalEndTime());
        //上一次缴费开始日期
        carOrder.setPrevStartTime(carInfo.getLocalStartTime());
        carOrder.setCarNo(carInfo.getCarNo());
        carOrder.setParkId(carInfo.getParkId());
        carOrder.setSn(sn);
        carOrder.setCarTypeName(carInfo.getCarTypeName());
        carOrder.setOrderType(CarOrderTypeEnum.ORDER_TYPE_MONTHS.getCode()); //月卡
        carOrder.setCheckStatus(CheckStatusEnum.CHECK_STATUS_YES.getCode());
        carOrder.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode()); //默认未同步
        carOrder.setPayStatus(PayStatusEnum.PAY_STATUS_NO.getCode());
        carOrder.setUserId(carInfo.getOwnerId()); //业主id
        carOrder.setUserMobile(carInfo.getMobile()); //车主号码
        carOrder.setTenantId(user.getTenantId());
        carOrder.setPayChannel(payConfig.getChannel());
        if ("FFT".equals(payConfig.getChannel())){
            String payResCode = "-1";
            String request = "";
            JSONObject payRes = null;

            //调用银行接口
            List<Object> list = new ArrayList<Object>();
            FFTFeeItem feeMoney = new FFTFeeItem();
            feeMoney.setSubjectName("停车费");
            feeMoney.setDetailAmt(carOrder.getPayAmount().toString());
            list.add(feeMoney);
            FFTCreateOrder fftCreateOrder = new FFTCreateOrder();
            fftCreateOrder.setReqNo(sn);
            fftCreateOrder.setOrgNo(payConfig.getOrgNo());
            fftCreateOrder.setVillageName(payConfig.getProjectName());
            String preStr = carOrder.getPayQRCode().substring(0, 2);
            if (preStr.equals("28")){ // 支付宝二维码
                carOrder.setPayType(PayTypeEnum.PAY_METHOD_ALIPAY.getCode().toString());
                fftCreateOrder.setPaymentType("03");
            }else {
                carOrder.setPayType(PayTypeEnum.PAY_METHOD_WEIXINPAY.getCode().toString());
                fftCreateOrder.setPaymentType("04");
            }
            fftCreateOrder.setPaymentModel("00");
            fftCreateOrder.setOrderAmt(carOrder.getPayAmount());
            fftCreateOrder.setNotifyUrl(payConfig.getNotifyUrl());
            fftCreateOrder.setOriOrderDetails(list);
            fftCreateOrder.setAddress(payConfig.getAddress());
            fftCreateOrder.setCity(payConfig.getCity());
            fftCreateOrder.setProvince(payConfig.getProvince());
            fftCreateOrder.setCounty(payConfig.getCounty());
            request = JSONObject.toJSONString(fftCreateOrder);
            log.info("月卡车加密参数===="+request);
            String cipher = Sm4Util.encryptEcb(fftEncryptKey, request);
            try {
                payRes = ComUtil.doPost(payConfig.getPayUrl()+"/ori/createOrder",cipher,fftEncryptKey);
                log.info("月卡车返回json========="+ payRes);
                payResCode = payRes.getString("returnCode");
            }catch (Exception e){
                log.error("月卡车缴费调用下单接口异常:{}",e);
                return Result.error("月卡车缴费调用银行支付接口繁忙！");
            }
            carOrder.setRequest(request);
            if ("0000".equals(payResCode)){
                String  data = payRes.getString("data");
                JSONObject jsonObject = JSONObject.parseObject(data);
                String transNo = jsonObject.getString("transNo");
                carOrder.setResponse(JSONObject.toJSONString(jsonObject));
                carOrder.setPayMode(PayModeEnum.PAY_MODE_SCANNER.getCode());
                carOrder.setTransNo(transNo);
                carOrderMapper.insert(carOrder);
                Map<String, String> param = new HashMap<>();
                param.put("payUserCode", carOrder.getPayQRCode());
                param.put("transNo", transNo);
                String paramStr = JSONObject.toJSONString(param);
                String jsonmin = Sm4Util.encryptEcb(fftEncryptKey, paramStr);
                String url = payConfig.getPayUrl() +"/ori/payOrder";
                try {
                    JSONObject res = ComUtil.doPost(url, jsonmin, fftEncryptKey);
                    log.info("月卡车付费通ori/payOrder请求结果=========" + res);
                    String code = res.getString("returnCode");
                    String msg = res.getString("returnMsg");
                    if ("0000".equals(code)){
                        String queryData = "00";
                        final long timeInterval = 5000;
                        int i = 1;
                        Map<String, String> qParam = new HashMap<>();
                        qParam.put("transNo", transNo);
                        String qParamStr = JSONObject.toJSONString(qParam);
                        String qJsonMin = Sm4Util.encryptEcb(fftEncryptKey, qParamStr);
                        String queryUrl = payConfig.getPayUrl() +"/ori/queryPayResult";
                        while (i <= 20){
                            try {
                                JSONObject queryRes = ComUtil.doPost(queryUrl, qJsonMin, fftEncryptKey);
                                log.info("月卡车ori/queryPayResult订单查询结果=========" + res);
                                queryData = queryRes.getString("data");
                                if ("02".equals(queryData)){
                                    CarPayNotify stu = new CarPayNotify();
                                    stu.setTransNo(transNo);
                                    stu.setOrderId(carOrder.getSn());
                                    stu.setPaymentAmt(carOrder.getPayAmount().toString());
                                    stu.setPaymentTime(DateUtils.date2Str(new Date(),DateUtils.yyyymmddhhmmss));
                                    carPayNotify(stu);
                                    break;
                                }else if ("03".equals(queryData)){
                                    log.info("月卡车支付查询状态为支付失败,订单号:{}",transNo);
                                    break;
                                }else {
                                    Thread.sleep(timeInterval);
                                }
                            }catch (Exception ex){
                                log.error("月卡车支付状态查询异常:执行次数:{},订单号:{}",ex,i,transNo);
                                return Result.error("支付接口请求失败");
                            }finally {
                                i++;
                            }
                        }
                        return Result.ok(queryData);
                    }else {
                        return Result.error(msg);
                    }
                }catch (Exception ex){
                    log.info("月卡车支付接口请求失败", ex);
                    return Result.error("月卡车支付接口请求失败");
                }
            }else {
                return Result.error("月卡车银行下单失败");
            }
        }else {
            return Result.error("月卡车不支持的银行渠道");
        }
    }

    @Override
    public Result carBlueInvoice(CarOrder carOrder) {
        if (null == carOrder){
            return Result.error("开票订单异常");
        }
        log.info("月卡车发票订单:{}", carOrder);
        try {
            if (InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode().equals((carOrder.getInvoiceStatus() + ""))) {
                if (StringUtils.isEmpty(carOrder.getFeeItemId())){
                    log.warn("月卡开票feeItemId 为空，订单号sn====={}", carOrder.getSn());
                    return Result.error("未配置开票收费项，开票失败！");
                }

                // todo 后续配置在表里
                if (ComUtil.isLastDayOfMonth(new Date())){
                    log.info("当月最后一天停止开票");
                    return Result.error("当月最后一天停止开票!");
                }

                // 电子发票
                ChargeInvoiceRequest invoiceReqDetail = new ChargeInvoiceRequest();
                invoiceReqDetail.setProjectId(carOrder.getProjectId());
                invoiceReqDetail.setGmfMc(carOrder.getInvoiceName());
                invoiceReqDetail.setAddress(carOrder.getInvoiceAddress());
                invoiceReqDetail.setPayMethod(Integer.valueOf(carOrder.getPayType()));
                invoiceReqDetail.setPayMode(carOrder.getPayMode());
                invoiceReqDetail.setCreateTime(new Date());
                invoiceReqDetail.setFeeitemId(carOrder.getFeeItemId());
                invoiceReqDetail.setDelFlag("0");
                invoiceReqDetail.setOrderNum(carOrder.getSn());
                invoiceReqDetail.setTenantId(carOrder.getTenantId());
                invoiceReqDetail.setRemarks("月卡车："+ carOrder.getCarNo() + "\n" + "续费周期：" + ComUtil.dateTimeFmt(carOrder.getCoverStartTime(), "yyyy-MM-dd") + ">" + ComUtil.dateTimeFmt(carOrder.getCoverEndTime(),"yyyy-MM-dd"));
                if (StringUtils.isNotEmpty(carOrder.getInvoiceEmail())) {
                    invoiceReqDetail.setEmail(carOrder.getInvoiceEmail());
                }
                if (StringUtils.isNotEmpty(carOrder.getUserMobile())) {
                    invoiceReqDetail.setTel(carOrder.getUserMobile());
                }
                if (StringUtils.isNotEmpty(carOrder.getInvoiceEin())) {
                    invoiceReqDetail.setEin(carOrder.getInvoiceEin());
                }
                if (StringUtils.isNotEmpty(carOrder.getInvoiceAccount())) {
                    invoiceReqDetail.setAccount(carOrder.getInvoiceAccount());
                }
                double maxMoney = 9999;
                // 分多次开金额大于10000的票
                double amount = carOrder.getPayDue().doubleValue();
                int times = (int)(amount/maxMoney);
                for (int i = 0; i < times; i++){
                    invoiceReqDetail.setMoney(maxMoney);
                    log.info("invoiceReqDetail====:{}", invoiceReqDetail);
                    feignChargeService.openBlue(JSON.toJSONString(invoiceReqDetail), invoiceReqDetail.getTenantId());
                    Thread.sleep(500);
                }
                invoiceReqDetail.setMoney(amount - times*maxMoney);
                log.info("invoiceReqDetail====:{}", invoiceReqDetail);
                feignChargeService.openBlue(JSON.toJSONString(invoiceReqDetail), invoiceReqDetail.getTenantId());
                return Result.ok("开票成功！");
            }
        } catch (Exception ex) {
            log.error("开票失败，订单号:{}, 错误信息：{}",carOrder.getSn(), ex);
            return Result.error("开票失败！");
        }
        return Result.error("选择非电子发票");
    }

    @Override
    public Result checkOrderByTransNo(String parkId, String transNo) {
//        //根据项目ID获取到对应的支付配置
////        CarPayConfig payConfig = carOrderMapper.getCarPayConfig(parkId, "offline");
////        Map<String, String> param = new HashMap<>();
////        param.put("transNo", transNo);
////        String paramStr = JSONObject.toJSONString(param);
////        String jsonmin = Sm4Util.encryptEcb(fftEncryptKey, paramStr);
////        String url = payConfig.getPayUrl() +"/ori/queryPayResult";
////        try {
////            JSONObject res = ComUtil.doPost(url, jsonmin, fftEncryptKey);
////            log.info("月卡车付费通ori/queryPayResult订单查询结果=========" + res);
////            String code = res.getString("returnCode");
////            String msg = res.getString("returnMsg");
////            if ("0000".equals(code)){
////                return Result.ok(res);
////            }else {
////                return Result.error(msg);
////            }
////        }catch (Exception ex){
////            log.info("月卡车支付接口请求失败", ex);
////            return Result.error("月卡车支付接口请求失败");
////        }
        return null;
    }

    @Override
    public List<CarOrder> findPage(Page<CarOrder> page, CarOrder carOrder) {
        carOrder.setTenantId(SsoUtil.getLoginUser().getTenantId());
        return carOrderMapper.findPage(page,carOrder);
    }

    @Override
    public void updateSyncStatus(String id, Integer syncStatus,String remarks) {
        carOrderMapper.updateSyncStatus(id,syncStatus,remarks);
    }

    @Override
    public CarOrder getOrderBySn(String sn) {
        return carOrderMapper.getOrderBySn(sn);
    }

    @Override
    public CarOrder getEndChargeTime(String carId, Integer carOrderType) {
        return carOrderMapper.getEndChargeTime(carId,carOrderType);
    }

    @Override
    public List<CarDayReportRespVo> findGroupList(CarDayReportReqVo carDayReportReqVo) {
        return carOrderMapper.findGroupList(carDayReportReqVo);
    }

    @Override
    public List<DayReportRespVo> apiFindGroupList(DayReportReqVo dayReportReqVo){
        return carOrderMapper.apiFindGroupList(dayReportReqVo);
    };

    /**
     * AB车退款逻辑
     * @param carOrder 订单信息
     * @param carInfo 车辆信息
     * @param carParkInfo 车场信息
     * @return
     */
    public Result refundAB(CarOrder carOrder, CarInfo carInfo, CarParkInfo carParkInfo){
        try {
            StringBuilder sb = new StringBuilder();
            List<CarInfo> carPortCarList = carInfoService.getByCarPortId(carInfo.getCarPortId());
            //首次充值退款
            if (carOrder.getPrevEndTime() == null){
                    for (int i = 0; i < carPortCarList.size(); i++){
                        //已经同步车辆
                        if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(carPortCarList.get(i).getSyncStatus())){
                            //删除车禁中车辆信息
                            ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                            req.setPark_id(carParkInfo.getOutSysId());
                            req.setPlate_number(carPortCarList.get(i).getCarNo());
                            Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                            if (syncRes.isSuccess()){
                                //修改车辆起始到期日 修同步状态
                                carPortCarList.get(i).setLocalStartTime(null);
                                carPortCarList.get(i).setLocalEndTime(null);
                                carPortCarList.get(i).setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                                carInfoService.updateById(carPortCarList.get(i));
                                sb.append(carPortCarList.get(i).getCarNo()+"(退款成功),");
                                log.info("AB车辆退款：{}成功", carPortCarList.get(i).getCarNo());
                            }else{
                                log.error("AB车辆退款同步线下车场失败信息",syncRes.getMessage());
                                return Result.error("AB车辆退款删除车禁信息失败！");
                            }
                        }else {
                            //修改车辆起始到期日 修同步状态
                            carPortCarList.get(i).setLocalStartTime(null);
                            carPortCarList.get(i).setLocalEndTime(null);
                            carPortCarList.get(i).setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                            carInfoService.updateById(carPortCarList.get(i));
                            sb.append(carPortCarList.get(i).getCarNo()+"(退款成功),");
                        }
                    }
                    CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                    carPort.setLocalStartTime(null);
                    carPort.setLocalEndTime(null);
                    //更新车位信息
                    carPortService.updateById(carPort);
                }else {
                for(CarInfo portCat : carPortCarList){
                    CarInfo info = carInfoService.getByCarId(portCat.getId());
                    //月卡转临停退款不做车辆信息更新，在出场时更新为车位时间
                    if(info.getLocalStartTime().equals(info.getLocalEndTime())){continue;}
                    //已经同步车辆
                    if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(info.getSyncStatus())&& !info.getLocalStartTime().equals(info.getLocalEndTime())){
                        //车禁信息更新
                        ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                        rentReq.setPark_id(carParkInfo.getOutSysId());
                        rentReq.setCarmodelid(info.getOutCarModel());
                        rentReq.setCartypeid(info.getOutCarType());
                        rentReq.setPlate_number(info.getCarNo());
                        rentReq.setEmp_moblie(carOrder.getUserMobile());
                        rentReq.setEmp_name(carOrder.getUserMobile());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        //开始时间
                        rentReq.setBegindate(sdf.format(carOrder.getPrevStartTime()));
                        //结束时间 = 前次的缴费截止日期
                        rentReq.setEnddate(sdf.format(carOrder.getPrevEndTime()));
                        Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
                        if (rentResult.isSuccess()){
                            sb.append(info.getCarNo()+"(退款成功),");
                            //修改车辆信息
                            info.setLocalStartTime(carOrder.getPrevStartTime());
                            info.setLocalEndTime(carOrder.getPrevEndTime());
                            carInfoService.updateFeeDate(info);
                        }else {
                            log.error("AB车辆退款同步线下车场失败信息",rentResult.getMessage());
                            return Result.error("AB车辆退款同步线下车场失败！");
                        }
                    }else {
                        //修改车辆信息
                        info.setLocalStartTime(carOrder.getPrevStartTime());
                        info.setLocalEndTime(carOrder.getPrevEndTime());
                        carInfoService.updateFeeDate(info);
                    }
                }
                CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                carPort.setLocalEndTime(carOrder.getPrevEndTime());
                //更新车位信息
                carPortService.updateById(carPort);
            }
            //修改订单状态
            carOrder.setRefundStatus(RefundStatusEnum.REFUND_STATUS_YES.getCode());
            carOrder.setRefundDate(new Date());
            carOrder.setRefundBy(SsoUtil.getLoginUser().getId());
            carOrder.setRemarks(carOrder.getRemarks() + "["+ sb.toString() +"]");
            this.updateById(carOrder);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("车辆缴费订单退款异常:"+e.getMessage());
        }
        return Result.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result refundCharge(String orderId) {
        try {
            CarOrder carOrder = this.getById(orderId);
            if (carOrder == null){
                return Result.error("未查询到当前账单信息");
            }
            if (CarOrderTypeEnum.ORDER_TYPE_TEMP.getCode() == carOrder.getOrderType()){
                return Result.error("临停车订单暂不支持退款！");
            }
            /*if (!PayModeEnum.PAY_MODE_OFFLINE.getCode().equals(carOrder.getPayMode())){
                return Result.error("线上订单暂不支持退款！");
            }*/
            CarInfo carInfo = carInfoService.getByCarId(carOrder.getCarId());
            CarParkInfo carParkInfo = carParkInfoService.getById(carInfo.getParkId());
            if (carInfo == null){
                return Result.error("未查询到退款车辆信息");
            }
            if(!PayStatusEnum.PAY_STATUS_YES.getCode().equals(carOrder.getPayStatus()) ||
                    !CheckStatusEnum.CHECK_STATUS_YES.getCode().equals(carOrder.getCheckStatus()) ||
                    CarSyncStatusEnum.SYNC_STATUS_NO.getCode().equals(carOrder.getSyncStatus()) ||
                    RefundStatusEnum.REFUND_STATUS_YES.getCode().equals(carOrder.getRefundStatus())){
                return Result.error("当前状态订单不允许操作！");
            }
            //获取最后一次充值订单信息
            CarOrder lastOrder = carOrderMapper.getByCarNo(carOrder.getCarNo());
            //当退款订单与lastorder 充值时间 和 id 相等 允许退款
            if (!lastOrder.getPayTime().equals(carOrder.getPayTime()) || !lastOrder.getId().equals(carOrder.getId())){
                return Result.error("只允许退款最后一次充值订单");
            }
            if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                return refundAB(carOrder, carInfo, carParkInfo);
            }
            //第一次充值退款特殊处理
            if (carOrder.getPrevEndTime() == null){
                //已经同步车辆
                if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(carInfo.getSyncStatus())){
                    //删除车禁中车辆信息
                    ForeignCarMonthlyRentReq req = new ForeignCarMonthlyRentReq();
                    req.setPark_id(carParkInfo.getOutSysId());
                    req.setPlate_number(carInfo.getCarNo());
                    //删除车禁信息
                    Result<String> syncRes = foreignCarJGSService.delMonthlyRent(req);
                    if (syncRes.isSuccess()){
                        //修改车辆起始到期日 修同步状态
                        carInfo.setLocalStartTime(null);
                        carInfo.setLocalEndTime(null);
                        carInfo.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                        carInfoService.updateById(carInfo);
                        //修改订单状态
                        carOrder.setRefundStatus(RefundStatusEnum.REFUND_STATUS_YES.getCode());
                        carOrder.setRefundDate(new Date());
                        carOrder.setRefundBy(SsoUtil.getLoginUser().getId());
                        this.updateById(carOrder);
                    }else{
                        log.error("删除车禁信息失败",syncRes.getMessage());
                        return Result.error("删除车禁信息失败！");
                    }
                }else {
                    //修改车辆起始到期日 修同步状态
                    carInfo.setLocalStartTime(null);
                    carInfo.setLocalEndTime(null);
                    carInfo.setSyncStatus(CarSyncStatusEnum.SYNC_STATUS_NO.getCode());
                    carInfoService.updateById(carInfo);
                    //修改订单状态
                    carOrder.setRefundStatus(RefundStatusEnum.REFUND_STATUS_YES.getCode());
                    carOrder.setRefundDate(new Date());
                    carOrder.setRefundBy(SsoUtil.getLoginUser().getId());
                    this.updateById(carOrder);
                }
            }else{
                //已经同步车辆
                if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(carInfo.getSyncStatus())){
                    //车禁信息更新
                    ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                    rentReq.setPark_id(carParkInfo.getOutSysId());
                    rentReq.setCarmodelid(carInfo.getOutCarModel());
                    rentReq.setCartypeid(carInfo.getOutCarType());
                    rentReq.setPlate_number(carInfo.getCarNo());
                    rentReq.setEmp_moblie(carOrder.getUserMobile());
                    rentReq.setEmp_name(carOrder.getUserMobile());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //开始时间 todo 充值那边可能有问题
                    rentReq.setBegindate(sdf.format(carOrder.getPrevStartTime()));
                    //结束时间 = 前次的缴费截止日期
                    rentReq.setEnddate(sdf.format(carOrder.getPrevEndTime()));
                    Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
                    if (rentResult.isSuccess()){
                        //修改订单退款状态
                        carOrder.setRefundStatus(RefundStatusEnum.REFUND_STATUS_YES.getCode());
                        carOrder.setRefundDate(new Date());
                        carOrder.setRefundBy(SsoUtil.getLoginUser().getId());
                        this.updateById(carOrder);
                        //修改车辆信息
                        carInfo.setLocalStartTime(carOrder.getPrevStartTime());
                        carInfo.setLocalEndTime(carOrder.getPrevEndTime());
                        carInfoService.updateFeeDate(carInfo);
                    }else {
                        log.error("同步线下车场失败信息",rentResult.getMessage());
                        return Result.error("同步线下车场失败！");
                    }
                }else{
                    //修改订单退款状态
                    carOrder.setRefundStatus(RefundStatusEnum.REFUND_STATUS_YES.getCode());
                    carOrder.setRefundDate(new Date());
                    carOrder.setRefundBy(SsoUtil.getLoginUser().getId());
                    this.updateById(carOrder);
                    //修改车辆信息
                    carInfo.setLocalStartTime(carOrder.getPrevStartTime());
                    carInfo.setLocalEndTime(carOrder.getPrevEndTime());
                    carInfoService.updateFeeDate(carInfo);
                }
            }
            if ((""+carOrder.getInvoiceStatus()).equals(InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode())){
                List<ChargeInvoiceRequest> list = this.invoiceRequestListBySn(carOrder.getSn());
                for (ChargeInvoiceRequest temp : list){
                    feignChargeService.openRed(JSON.toJSONString(temp), temp.getTenantId());
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("车辆缴费订单退款异常:"+e.getMessage());
        }
        return Result.ok();
    }

    @Override
    public List<ChargeInvoiceRequest> invoiceRequestListBySn(String sn) {
        return carOrderMapper.invoiceRequestListBySn(sn);
    }

    @Override
    public ChargeInvoiceRequest invoiceRequestByFpqqlsh(String fpqqlsh) {
        return carOrderMapper.invoiceRequestByFpqqlsh(fpqqlsh);
    }

    /**
     *
     *  公众号支付回调
     * */
    @Transactional(readOnly = false)
    public Result carPayNotify(CarPayNotify stu) {
        log.info("临停支付回调销账接受参数:{}",stu);
        String lockKey = RedisKeyConstant.CAR_ORDER_KEY + stu.getOrderId();
        boolean getLock = lockClient.tryLock(lockKey,0,120);
        if (!getLock) {
            log.warn("车辆支付回调,订单支付中transNo:{},sn:{}",stu.getTransNo(),stu.getOrderId());
            return Result.error("支付回调中！");
        }
        CarOrder order =  carOrderMapper.getOrderBySn(stu.getOrderId());
        //通知成功
        if (order == null) {
            return Result.error("订单不存在！");//销账失败
        }
        //已支付。直接结束
        if (order.getPayStatus() == 1) {
            return Result.error("订单已支付！");
        }
        try {
            CarParkInfo carParkInfo = carParkInfoService.getByParkId(order.getParkId());
            if (order.getOrderType() == 1){
                CarInfo carInfo = carInfoService.getByCarId(order.getCarId());
                //正常缴费 && 不是首次缴费只更新结束时间
                if((order.getChargeType() == null || CarChargeTypeEnum.CHARGE_TYPE_NORMAL.getCode().equals(order.getChargeType()+"")) && order.getPrevEndTime() != null ){
                    carInfo.setLocalEndTime(order.getCoverEndTime());
                }else {
                    carInfo.setLocalStartTime(order.getCoverStartTime());
                    carInfo.setLocalEndTime(order.getCoverEndTime());
                }
                carInfoService.updateFeeDate(carInfo);

                if (StringUtils.isNotBlank(carInfo.getCarPortId())){
                    //车位车 更新车位信息
                    CarPort carPort = carPortService.getById(carInfo.getCarPortId());
                    if (carPort == null){
                        log.info("未查询到当前车辆车位信息=={}", carInfo.getCarNo());
                    }else {
                        //车位第一次续费需要更新开始时间
                        if (carPort.getLocalStartTime() == null){
                            carPort.setLocalStartTime(carInfo.getLocalStartTime());
                        }
                        carPort.setLocalEndTime(carInfo.getLocalEndTime());
                        carPortService.updateById(carPort);
                        List<CarInfo> infoList =  carInfoService.getByCarPortId(carInfo.getCarPortId());
                        boolean synFlag = true;
                        for (CarInfo info : infoList){
                            //更新车位其他车辆信息（剔除上面已经更新的车辆 && 月卡开始结束时间相同车辆（ab临停））
                            if (!info.getCarNo().equals(carInfo.getCarNo()) && !info.getLocalStartTime().equals(info.getLocalEndTime())){
                                info.setLocalEndTime(carInfo.getLocalEndTime());//车位不能断缴只用修改结束时间
                                carInfoService.updateFeeDate(info);
                            }
                            // 同步车位下所有车辆日期到车场
                            CarParkInfo CPInfo = carParkInfoService.getById(info.getParkId());
                            ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                            rentReq.setPark_id(CPInfo.getOutSysId());
                            rentReq.setCarmodelid(info.getOutCarModel());
                            rentReq.setCartypeid(info.getOutCarType());
                            rentReq.setPlate_number(info.getCarNo());
                            rentReq.setEmp_moblie(order.getUserMobile());
                            rentReq.setEmp_name(order.getUserMobile());
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            rentReq.setBegindate(sdf.format(info.getLocalStartTime()));
                            rentReq.setEnddate(sdf.format(order.getCoverEndTime()));
                            Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
                            if (!rentResult.isSuccess()){
                                synFlag = false;
                                log.info("同步车位车辆日期失败{}", info);
                            }
                        }
                        if (synFlag){
                            //更新订单表
                            carOrderMapper.updateOrderCarPay(stu.getOrderId(),stu.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),stu.getPaymentTime(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(),null);
                        } else {
                            carOrderMapper.updateOrderCarPay(stu.getOrderId(),stu.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),stu.getPaymentTime(), null,null);
                        }
                    }
                } else {
                    // 非车位车 同步月卡日期到车场
                    ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
                    rentReq.setPark_id(carParkInfo.getOutSysId());
                    rentReq.setCarmodelid(carInfo.getOutCarModel());
                    rentReq.setCartypeid(carInfo.getOutCarType());
                    rentReq.setPlate_number(carInfo.getCarNo());
                    rentReq.setEmp_moblie(order.getUserMobile());
                    rentReq.setEmp_name(order.getUserMobile());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    rentReq.setBegindate(sdf.format(carInfo.getLocalStartTime()));
                    rentReq.setEnddate(sdf.format(order.getCoverEndTime()));

                    Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
                    if (rentResult.isSuccess()) {
                        //更新订单表
                        carOrderMapper.updateOrderCarPay(stu.getOrderId(), stu.toString(), PayStatusEnum.PAY_STATUS_YES.getCode(), stu.getPaymentTime(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(),null);
                    } else {
                        carOrderMapper.updateOrderCarPay(stu.getOrderId(), stu.toString(), PayStatusEnum.PAY_STATUS_YES.getCode(), stu.getPaymentTime(), null,null);
                        log.error("同步月卡车场失败信息", rentResult.getMessage());
                    }
                    order.setFeeItemId(carInfo.getFeeitemId());
                }
                this.carBlueInvoice(order);
            } else {
                ForeignCarIotPayTempReq carPayTempReq = new ForeignCarIotPayTempReq();
                if (carParkInfo != null){
                    carPayTempReq.setPark_id(carParkInfo.getOutSysId());
                }
                carPayTempReq.setOrder_id(stu.getOrderId());
                carPayTempReq.setOrder_no(order.getOrderNo());
                carPayTempReq.setPay_fee(order.getPayDue().toString());
                carPayTempReq.setPay_type("2");
                carPayTempReq.setPlate_number(order.getCarNo());
                // 临停支付通知接口
                Result<String> payTempRes =  foreignCarJGSService.payTempCost(carPayTempReq);
                if (payTempRes.isSuccess()){
                    //更新订单表
                    carOrderMapper.updateOrderCarPay(stu.getOrderId(),stu.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),stu.getPaymentTime(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(),null);
                } else {
                    carOrderMapper.updateOrderCarPay(stu.getOrderId(),stu.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),stu.getPaymentTime(), null,null);
                }
                if (StringUtils.isNotBlank(order.getCarNo())){
                    //更新优惠券绑定车牌状态为已使用
                    CarDerateDetails derateDetails = derateDetailsService.getDerateDetail(order.getCarNo());
                    if (derateDetails != null){
                        derateDetails.setStatus(CarDerateDetailStatusEnum.CAR_DERATE_DETAIL_STATUS_1.getCode());
                        derateDetails.setUseTime(new Date());
                        derateDetailsService.updateById(derateDetails);
                    }
                }
            }
            return Result.ok(order);
        } catch (Exception e) {
            log.error("临停支付回调更新订单表异常:{}",e);
            return Result.error("订单更新失败！");
        }
    }

    /**
     *  市公共平台支付回调
     * @param payCallBackReq
     * @return
     */
    @Override
    public ForeignResult carPayNotifySH(ForeignCarShPayCallBackReq payCallBackReq) {
        log.info("市公共平台支付回调接受参数:{}",payCallBackReq);
        String lockKey = RedisKeyConstant.CAR_ORDER_KEY + payCallBackReq.getOrderId();
        boolean getLock = lockClient.tryLock(lockKey,0,120);
        if (!getLock) {
            log.warn("车辆支付回调,订单支付中sn:{}",payCallBackReq.getOrderId());
            return ForeignResult.error("支付回调中！");
        }
        CarOrder order =  carOrderMapper.getOrderBySn(payCallBackReq.getOrderId());
        if (order == null) {
            return ForeignResult.error("订单不存在！");//销账失败
        }
        if (order.getPayStatus() == 1) { //已支付。直接结束
            return ForeignResult.error("订单已支付！");
        }
        if (order.getOrderType() == 1) {
            return ForeignResult.error("订单类型不支持！");
        }
        Integer payType = PayTypeEnum.PAY_METHOD_OTHER.getCode();
        if (payCallBackReq.getPayType() == 2) {
            payType = PayTypeEnum.PAY_METHOD_WEIXINPAY.getCode();
        } else if (payCallBackReq.getPayType() == 3) {
            payType = PayTypeEnum.PAY_METHOD_ALIPAY.getCode();
        }
        String payTime = DateUtils.formatShortTime(payCallBackReq.getPayTime(),DateUtils.datetimeFormat);
        ForeignCarIotPayTempReq carPayTempReq = new ForeignCarIotPayTempReq();
        CarParkInfo carParkInfo = carParkInfoService.getByParkId(order.getParkId());
        if (carParkInfo != null){
            carPayTempReq.setPark_id(carParkInfo.getOutSysId());
        }
        carPayTempReq.setOrder_id(payCallBackReq.getOrderId());
        carPayTempReq.setOrder_no(order.getOrderNo());
        carPayTempReq.setPay_fee(order.getPayDue().toString());
        carPayTempReq.setPay_type("2");
        carPayTempReq.setPlate_number(order.getCarNo());
        // 临停支付通知接口
        Result<String> payTempRes =  foreignCarJGSService.payTempCost(carPayTempReq);
        if (payTempRes.isSuccess()){
            //更新订单表
            carOrderMapper.updateOrderCarPay(payCallBackReq.getOrderId(),payCallBackReq.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),payTime, CarSyncStatusEnum.SYNC_STATUS_YES.getCode(),payType);
        } else {
            carOrderMapper.updateOrderCarPay(payCallBackReq.getOrderId(),payCallBackReq.toString(),PayStatusEnum.PAY_STATUS_YES.getCode(),payTime, null,payType);
        }
        if (StringUtils.isNotBlank(order.getCarNo())){
            //更新优惠券绑定车牌状态为已使用
            CarDerateDetails derateDetails = derateDetailsService.getDerateDetail(order.getCarNo());
            if (derateDetails != null){
                derateDetails.setStatus(CarDerateDetailStatusEnum.CAR_DERATE_DETAIL_STATUS_1.getCode());
                derateDetails.setUseTime(new Date());
                derateDetailsService.updateById(derateDetails);
            }
        }
        return ForeignResult.ok(order);
    }

    public CarOrder getOrderByTransNo(String transNo) {
        return carOrderMapper.getOrderByTransNo(transNo);
    }
}
